package com.leyou.trade.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.DEAD_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.ExchangeConstants.ORDER_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.DEAD_ORDER_QUEUE;
import static com.leyou.common.constants.MQConstants.QueueConstants.EVICT_ORDER_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.EVICT_ORDER_KEY;

/**
 * @author 虎哥
 */
@Configuration
public class MqConfig {

    /**
     * 订单超时未支付的时间，单位毫秒
     */
    private static final long ORDER_QUEUE_DELAY_TIME = 30000;

    @Bean("orderExchange")
    public TopicExchange orderExchange(){
        return new TopicExchange(ORDER_EXCHANGE_NAME, true, false);
    }

    @Bean("deadExchange")
    public TopicExchange deadExchange(){
        return new TopicExchange(DEAD_EXCHANGE_NAME, true, false);
    }

    @Bean
    public Queue deadOrderQueue(){
        // 死信队列参数
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        arguments.put("x-message-ttl", ORDER_QUEUE_DELAY_TIME);
        // 创建队列
        return QueueBuilder.durable(DEAD_ORDER_QUEUE).withArguments(arguments).build();
    }

    @Bean
    public Queue evictOrderQueue(){
        return new Queue(EVICT_ORDER_QUEUE);
    }

    @Bean
    public Binding bindingDeadQueue(){
        // 绑定死信队列和交换机
        return BindingBuilder.bind(deadOrderQueue()).to(orderExchange()).with(EVICT_ORDER_KEY);
    }
    @Bean
    public Binding bindingDeadExchange(){
        // 绑定队列和死信交换机
        return BindingBuilder.bind(evictOrderQueue()).to(deadExchange()).with(EVICT_ORDER_KEY);
    }

    @Bean
    public Jackson2JsonMessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}
